// Copyright (C) 2021-2022 Intel Corporation
// Copyright (C) 2024 CVAT.ai Corporation
//
// SPDX-License-Identifier: MIT

import React, { useState, useEffect } from 'react';
import Text from 'antd/lib/typography/Text';
import { cancelSecondReview, getReviewAnnotationListAsync } from 'actions/annotation-actions';

import Icon, { ExclamationCircleFilled } from '@ant-design/icons';
import { ArrowIcon } from 'icons';
import { Col, Tag, message, Collapse, Row } from 'antd';
import useAnnotation from 'hooks/useAnnotation';
import classNames from 'classnames';
import { useSelector, useDispatch } from 'react-redux';
import { CombinedState } from 'reducers';
import { useParams } from 'react-router-dom-v5-compat';
import { JobStatusEnum } from 'typings/annotion/task';
import { saveReviewLabel } from 'apis/annotation/task';
import CorrectRadio from './correct-radio';

interface Props {
    readonly: boolean;
    collapsed: boolean;
    attributes: any[];
    values: Record<number, string>;
    collapseLabel: JSX.Element;
    color: string;
    labelName: string;
    clientID: number | null;
    changeAttribute(attrID: number, value: string): void;
    collapse(): void;
}

export function attrValuesAreEqual(next: Record<number, string>, prev: Record<number, string>): boolean {
    const prevKeys = Object.keys(prev);
    const nextKeys = Object.keys(next);

    return (
        nextKeys.length === prevKeys.length &&
        nextKeys.map((key: string): boolean => prev[+key] === next[+key]).every((value: boolean) => value)
    );
}

function attrAreTheSame(prevProps: Props, nextProps: Props): boolean {
    return (
        nextProps.readonly === prevProps.readonly &&
        nextProps.collapsed === prevProps.collapsed &&
        nextProps.attributes === prevProps.attributes &&
        attrValuesAreEqual(nextProps.values, prevProps.values)
    );
}

function ItemAttributesComponent(props: Props): JSX.Element {
    const { collapsed, attributes, color, clientID, collapse } = props;
    const { annotationId } = useSelector((state: CombinedState) => state.annotation.secondReview);
    const {
        approval: { annotationData = {} },
        differenceObj,
    } = useAnnotation();
    const [origin = {}, firstReview = {}, secondReview = {}] = annotationData?.[clientID!] || [];
    const approvalStatus = secondReview?.approvalStatus;
    const params = useParams();
    const dispatch = useDispatch();

    const diff = differenceObj(origin, firstReview);
    const firstReviewClass = classNames({
        'text-base': true,
        'text-[#F53F3F]': diff === true,
    });

    const [checkedVal, setCheckVal] = useState<0 | 1 | undefined>();

    useEffect(() => {
        setCheckVal(secondReview.correctIndex);
    }, [secondReview]);
    const handleSubmit = async (checked: boolean, index: number) => {
        const data = Object.keys(annotationData).map((key) => {
            if (key === clientID!.toString()) {
                return {
                    ...annotationData[key][2],
                    approvalStatus: checked ? 2 : 1, // 初审修改，复审已核
                    // 已纠正
                    isCorrect: checked ? 1 : undefined,
                    // 正确数据 0标注员 1 初审 2复审
                    correctIndex: checked ? index : undefined,
                };
            }
            return annotationData[key][2];
        });
        try {
            await saveReviewLabel({
                id: annotationId,
                subTaskId: params.sid!,
                cvatTaskId: +params.tid!,
                jobId: +params.jid!,
                annotion: JSON.stringify(data),
                auditStatus: JobStatusEnum.WAITING_SECOND_REVIEW,
            });
            dispatch(cancelSecondReview());
            dispatch(getReviewAnnotationListAsync(+params.jid!, params.sid!));
            message.success('修改成功');
        } catch (error) {
            console.log(error);
        }
    };
    const changeLabelUser = (value: boolean) => {
        const val = value ? 0 : undefined;
        setCheckVal(val);
        handleSubmit(value, 0);
    };
    const changeLabelFirst = (value: boolean) => {
        const val = value ? 1 : undefined;
        setCheckVal(val);
        handleSubmit(value, 1);
    };

    return (
        <div>
            {approvalStatus && secondReview.correctIndex !== 2 ? (
                <>
                    {/* 未纠正 */}
                    <div className='bg-[#FFF7E8] px-3 py-9px mb-3 w-full'>
                        <ExclamationCircleFilled className='text-[#FF7D00] mr-2' />
                        <span>审核状态：{approvalStatus === 1 ? '初审修改、复审待核' : '初审修改、复审已核'}</span>
                    </div>

                    <div className='bg-white p-3 rounded-md' style={{ border: '1px solid #E9EAED' }}>
                        <div>
                            <div className='font-bold text-base mb-3 font-bold'>标注员</div>
                            <div className='flex items-center justify-between'>
                                <div>
                                    <Tag color={origin.color}>{clientID}</Tag>
                                    <span className='text-base'>{origin.label?.name}</span>
                                </div>
                                <CorrectRadio checked={checkedVal === 0} onChange={changeLabelUser} />
                            </div>
                            <div className='!bg-[#F7F8FA] p-3 mt-3 rounded space-y-3'>
                                {attributes.map(
                                    (attribute: any): JSX.Element => (
                                        <Row
                                            key={attribute.id}
                                            align='middle'
                                            justify='start'
                                            className='cvat-object-item-attribute-wrapper '
                                            gutter={[16, 0]}
                                        >
                                            <Col span={24}>
                                                <span className='text-[#86909C]'>{attribute.name}：</span>
                                                {origin?.attributes?.[attribute.id]}
                                            </Col>
                                        </Row>
                                    ),
                                )}
                            </div>
                        </div>
                        <div className='mt-18px'>
                            <div className='font-bold text-base mb-3 font-bold'>初审员</div>
                            <div className='flex items-center justify-between'>
                                <div>
                                    <Tag color={firstReview.color}>{clientID}</Tag>
                                    <span className={firstReviewClass}>{firstReview.label?.name}</span>
                                </div>
                                <CorrectRadio checked={checkedVal === 1} onChange={changeLabelFirst} />
                            </div>
                            <div className='!bg-[#F7F8FA] p-3 mt-3 rounded space-y-3'>
                                {firstReview?.label?.attributes.map(
                                    (attribute: any): JSX.Element => (
                                        <Row
                                            key={attribute.id}
                                            align='middle'
                                            justify='start'
                                            className='cvat-object-item-attribute-wrapper '
                                            gutter={[16, 0]}
                                        >
                                            <Col span={24}>
                                                <span className='text-[#86909C]'>{attribute.name}：</span>
                                                <span
                                                    className={
                                                        Array.isArray(diff) && diff.includes(attribute.id.toString())
                                                            ? 'text-[#F53F3F]'
                                                            : ''
                                                    }
                                                >
                                                    {firstReview?.attributes?.[attribute.id]}
                                                </span>
                                            </Col>
                                        </Row>
                                    ),
                                )}
                            </div>
                        </div>
                    </div>
                </>
            ) : (
                <div className='p-3 w-full box-border'>
                    {approvalStatus === 2 && (
                        <div className='bg-[#FFF7E8] px-3 py-9px mb-3 w-full'>
                            <ExclamationCircleFilled className='text-[#FF7D00] mr-2' />
                            <span>审核状态：初审修改、复审已核</span>
                        </div>
                    )}

                    <Collapse
                        className='cvat-objects-sidebar-state-item-collapse'
                        activeKey={collapsed ? [] : ['details']}
                        onChange={collapse}
                        expandIconPosition='end'
                        collapsible='icon'
                        expandIcon={({ isActive }) => (
                            <Icon component={ArrowIcon} className={isActive ? 'rotate-0' : 'rotate-180'} />
                        )}
                        items={[
                            {
                                key: 'details',
                                label: (
                                    <div>
                                        <Tag color={color}>{clientID}</Tag>
                                        <Text className='text-base'>{secondReview.label?.name}</Text>
                                    </div>
                                ),
                                children: (
                                    <div className='!bg-[#F7F8FA] p-3 mt-3 rounded space-y-3'>
                                        {secondReview.label?.attributes.map(
                                            (attribute: any): JSX.Element => (
                                                <Row
                                                    key={attribute.id}
                                                    align='middle'
                                                    justify='start'
                                                    className='cvat-object-item-attribute-wrapper '
                                                    gutter={[16, 0]}
                                                >
                                                    <Col span={24}>
                                                        <Text className='text-[#86909C]'>{attribute.name}：</Text>
                                                        {secondReview.attributes?.[attribute.id]}
                                                    </Col>
                                                </Row>
                                            ),
                                        )}
                                    </div>
                                ),
                            },
                        ]}
                    />
                </div>
            )}
        </div>
    );
}

export default React.memo(ItemAttributesComponent, attrAreTheSame);
